﻿using LightDataAccess;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Web;
using WebDemo.Domain;

namespace WebDemo.Data
{
    public class GPSRepository
    {
        private static readonly string dbkey = "GPSTrackDB";

        DbConnection GetConn()
        {
            return DBFactory.CreateConnection(dbkey);
        }

        public IEnumerable<GpsTrackInfo> SelectTopNRecords(int count)
        {
            IEnumerable<GpsTrackInfo> result = null;

            using (var conn = GetConn())
            {
                CmdParams param = new CmdParams();
                param.Add("@Count", count);

                //result = DBTools.ReadCollection<GpsTrackInfo>(conn, string.Format("SELECT * FROM gpstrackinfo LIMIT {0}", id), null);

                //result = DBTools.ReadCollection<GpsTrackInfo>(conn, "SELECT * FROM gpstrackinfo LIMIT @Count", param,
                //    dr => new GpsTrackInfo()
                //{
                //    ID = Convert.ToInt64(dr["ID"]),
                //    Mobile = dr["Mobile"].ToString(),
                //    Lon = Convert.ToSingle(dr["Lon"]),
                //    Lat = Convert.ToSingle(dr["Lat"]),
                //    Radius = Convert.ToSingle(dr["Radius"]),
                //    Direction = Convert.ToSingle(dr["Direction"]),
                //    Speed = Convert.ToSingle(dr["Speed"]),
                //    Province = dr["Province"].ToString(),
                //    City = dr["City"].ToString(),
                //    District = dr["District"].ToString(),
                //    Address = dr["Address"].ToString(),
                //    GPSTime = dr["GPSTime"].ToString(),
                //});

                result = DBTools.ReadCollection<GpsTrackInfo>(conn, "SELECT * FROM gpstrackinfo LIMIT @Count", param);
            }
            Thread.Sleep(10000);

            return result;
        }

        public IEnumerable<GpsTrackInfo> SelectByAddress(string address)
        {
            IEnumerable<GpsTrackInfo> result = null;
            CmdParams param = new CmdParams();
            param.Add("@Address", "马驹桥1桥南200米");

            using (var conn = GetConn())
            {
                result = DBTools.ReadCollection<GpsTrackInfo>(conn, "SELECT * FROM gpstrackinfo where address=@Address LIMIT 100", param);
            }

            Thread.Sleep(10000);

            return result;
        }

        public void Create(GpsTrackInfo record)
        {
            DBTools.InsertObject(GetConn(), record, "GpsTrackInfo", DbSettings.MySQL);
        }
    }
}